package com.dfec.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dfec.utils.ResponseUtil;

/**
 * Servlet Filter implementation class Referer
 */
//@WebFilter(filterName = "referer", description = "防盗链验证", urlPatterns = { "/*" })
public class Referer implements Filter {

    /**
     * Default constructor. 
     */
    public Referer() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		// 从 HTTP 头中取得 Referer 值
		 String referer=((HttpServletRequest) request).getHeader("Referer");
		 // 判断 Referer 是否以 bank.example 开头
		 if((referer!=null) &&(referer.trim().startsWith("192.168.1.11"))){
		   // chain.doFilter(request, response);
		    ResponseUtil.sendScript((HttpServletResponse)response, referer);
		 }else{
		   ResponseUtil.sendScript((HttpServletResponse)response, "<script>for(var i=0;i<1;i++){alert('非法访问')}</script>");
		 } 
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
